<template>
  <TreeSelect v-model="selectedValue"
              @change="handleChange"
              label="title"
              :data="treeData"/>
</template>
<script>

import TreeSelect from './TreeSelect.vue'
import api from "@/common/api.js";
import utils from "@/common/utils.js";

export default {
  name: 'StuffDirSelect',
  props: {
    value: {
      type: [String, Number],
      default: undefined
    },
  },
  components: {
    TreeSelect
  },
  emits: ['input', 'change'],
  data() {
    return {
      selectedValue: undefined,
      treeOptions: {
        label: 'title',
        children: 'children',
        isLeaf: (data) => {
          return data.stuffType !== 'dir'
        }
      },
      treeData: [],
    }
  },
  mounted() {
    this.getTreeData();
  },
  watch: {
    value: {
      immediate: true,
      handler(val) {
        this.selectedValue = val
      }
    }
  },
  methods: {
    async getTreeData() {
      const {data} = await api.admin_getStuffList({limit: 1000, stuffType: 'dir'});
      const list = data.data.records;
      this.treeData = utils.buildTreeWithParentId(list, {
        id: 0,
        stuffType: 'dir',
        title: '所有素材',
      });
    },
    handleChange(value) {      
      this.$emit('input', value)
      this.$emit('change', value)
    }
  }
}
</script>
